package com.wushijia.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

/**
 * description: authenticated():只需要认证过后即可，不校验权限，资源认证服务
 *
 * .antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')"):表达式语法，完成复杂的权限控制 .antMatchers("/product/**").hasAuthority()：基于权限的控制
 * .antMatchers("/product/**").hasRole()：基于角色的控制
 *
 * @author yang
 * @date 2018/5/18 16:35
 */
@Configuration
public class OAuth2ServerConfig {

  /**
   * description: 提供/oauth/authorize,/oauth/token,/oauth/check_token,/oauth/confirm_access,/oauth/error; oauth2官方只有4种授权方式，不过spring
   * securityoauth2把refresh_token也归为authorizedGrantTypes的一种，有"client_credentials", "refresh_token", "authorization_code", "password", "implicit"
   *
   * @author yang 认证服务
   * @date 2018/5/22 17:11
   */
  @Configuration
  @EnableAuthorizationServer
  protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      clients.inMemory()
          .withClient("malldemo")
          .secret("pgDBd99tOX8d")
          .redirectUris("http://www.baidu.com")
          .authorizedGrantTypes("authorization_code", "refresh_token", "implicit", "password", "client_credentials")
          .scopes("webmall");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints
          .authenticationManager(authenticationManager)
          .userDetailsService(userDetailsService);
    }
  }
}
